package com.ydkfjs.utils;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.thread.NamedThreadFactory;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ydkfjs.constants.LoginConstant;
import com.ydkfjs.handler.GlobalUncaughtExceptionHandler;
import com.ydkfjs.mapper.UserMapper;
import com.ydkfjs.model.dto.IpResult;
import com.ydkfjs.model.po.IpDetail;
import com.ydkfjs.model.po.IpInfo;
import com.ydkfjs.model.po.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: hb
 * @CreateTime: 2024-04-15 20:35
 * @Version: 1.0
 */
@Slf4j
@Component
public class IpUtils {

    private final UserMapper userMapper;

    public IpUtils(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    // 定义线程池，核心线程数为1，最大线程数1，仅用于解析ip，排队延迟处理
    private static final ExecutorService EXECUTOR = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(500),
            new NamedThreadFactory("refresh-ipDetail", null, false,
                    GlobalUncaughtExceptionHandler.getInstance()));

    /**
     * 异步更新用户ip
     *
     * @param id
     */
    public void refreshIpDetailAsync(Long id, String ip, Integer status) {
        // 线程池异步处理
        EXECUTOR.execute(() -> {
            // 获取ip
            IpDetail ipDetail = TryGetIpDetailOrNullTreeTimes(ip);
            if (Objects.nonNull(ipDetail)) {
                if (status == LoginConstant.USER_REGISTER) {
                    // 更新用户ip
                    User update = new User();
                    update.setId(id);
                    IpInfo ipInfo = new IpInfo();
                    // 注册ip和注册归属地信息
                    ipInfo.setCreateIpDetail(ipDetail);
                    ipInfo.setCreateIp(ip);
                    update.setIpInfo(ipInfo);
                    update.setEndTime(LocalDateTime.now());
                    userMapper.updateById(update);
                } else {
                    User user = userMapper.selectById(id);
                    IpInfo ipInfo = user.getIpInfo();
                    ipInfo.setUpdateIp(ip);
                    ipInfo.setUpdateIpDetail(ipDetail);
                    user.setEndTime(LocalDateTime.now());
                    userMapper.updateById(user);
                }
                log.info("用户id: {} 的ip归属地更新成功!", id);
            }
        });
    }

    /**
     * 获取ip详情
     *
     * @param ip
     * @return
     */
    private IpDetail TryGetIpDetailOrNullTreeTimes(String ip) {
        // 重试三次
        for (int i = 0; i < 3; i++) {
            // 获取
            IpDetail ipDetail = getIpDetailOrNull(ip);
            if (Objects.nonNull(ipDetail)) {
                return ipDetail;
            }
            try {
                // 间隔两秒
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 请求开放ip解析接口
     *
     * @param ip
     * @return
     */
    public IpDetail getIpDetailOrNull(String ip) {
        String body = HttpUtil.get("https://ip.taobao.com/outGetIpInfo?ip=" + ip + "&accessKey=alibaba-inc");
        try {
            IpResult<IpDetail> result = JSONUtil.toBean(body, new TypeReference<IpResult<IpDetail>>() {
            }, false);
            if (result.isSuccess()) {
                return result.getData();
            }
        } catch (Exception ignored) {
        }
        return null;
    }

    //测试耗时结果 100次查询总耗时约170s，平均一次成功查询需要1s,可以接受
    //第99次成功,目前耗时：99545ms
    public void main(String[] args) {
        Date begin = new Date();
        IpDetail ipDetail = TryGetIpDetailOrNullTreeTimes("113.90.36.126");
        System.out.println(ipDetail.toString());
//        for (int i = 0; i < 100; i++) {
//            int finalI = i;
//            EXECUTOR.execute(() -> {
//
//                if (Objects.nonNull(ipDetail)) {
//                    Date date = new Date();
//                    System.out.println(String.format("第%d次成功,目前耗时：%dms", finalI, (date.getTime() - begin.getTime())));
//                }
//            });
//        }
    }

    public void destroy() throws InterruptedException {
        EXECUTOR.shutdown();
        if (!EXECUTOR.awaitTermination(30, TimeUnit.SECONDS)) {//最多等30秒
            if (log.isErrorEnabled()) {
                log.error("等待执行器 [{}] 终止时超时", EXECUTOR);
            }
        }
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    try {
                        ipAddress = InetAddress.getLocalHost().getHostAddress();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                }
            }
            // 通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null) {
                if (ipAddress.contains(",")) {
                    return ipAddress.split(",")[0];
                } else {
                    return ipAddress;
                }
            } else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
